package com.fingard.dsp.bank.directbank.fngrd01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IDeContract;
import com.fingard.dsp.bank.reqrespobj.contract.ContractState;
import com.fingard.dsp.bank.reqrespobj.decontract.ReqDeContract;
import com.fingard.dsp.bank.reqrespobj.decontract.RetAtsDeContract;
import com.fingard.dsp.bank.reqrespobj.decontract.detail.RetAtsDeContractDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Date;

public class FnGrd01DeContract extends FnGrd01Base implements IDeContract{

    @Override
    public RetAtsDeContract deContract(ReqDeContract p_req) throws Exception {
        RetAtsDeContract retAts = new RetAtsDeContract(p_req.reqHeader);
        RetAtsDeContractDetail tmpRetDetail = new RetAtsDeContractDetail();
        tmpRetDetail.reqSeqID = p_req.contractDetail.askNumber;
        try {
            FnGrd01Header bankHeader = new FnGrd01Header();
            bankHeader.CorpBankCode = getBankConfig().getMapValueByKey("corBankCodeMapping", p_req.contractDetail.recAct);
            if (StringHelper.isNullOrEmpty(bankHeader.CorpBankCode)) {
                WriteBankLogLn2("CorpBankCode为空，请配置corBankCodeMapping映射");
            }
            bankHeader.TransSeqID = getQryTransID();
            bankHeader.CommandCode="311A2";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("SignReq");
            xmlWriter.writeElementString("Flag", "1");/* 0:签约 1:解约*/
            xmlWriter.writeElementString("CorpAct", p_req.contractDetail.recAct);/* 企业方账号 */
            xmlWriter.writeElementString("ProtocolCode", p_req.contractDetail.authCode.split("__")[0]);/* 协议号 	*/
            /*签约适用指令
            111G1 单笔代收
            111B1 单笔部分留底扣款????	*/
            xmlWriter.writeElementString("ForCommandCode", "111G1");
            xmlWriter.writeElementString("CustAct", p_req.contractDetail.payAct);
            xmlWriter.writeElementString("CustName", p_req.contractDetail.payName);
            xmlWriter.writeElementString("CertType", convertCertTypeToBank(p_req.contractDetail.certType));
            xmlWriter.writeElementString("CertNum", p_req.contractDetail.certNum);
            xmlWriter.writeElementString("Mobile", p_req.contractDetail.cellPhone);
            //限额 单笔限额
            xmlWriter.writeElementString("LimitAmount", p_req.contractDetail.singleLimit);
            xmlWriter.writeElementString("DealStartDate", Format.Date8Format.format(new Date()));
            xmlWriter.writeElementString("DealEndDate", Format.Date8Format.format(new Date()));
            //回复短信的验证方式回复短信验证码方式
            //1短信回复 默认
            //2接口发送
            String tmpReplySmsType="";
            if ("1".equals(getBankConfig().getValueAsString("signConfirm"))) {
                tmpReplySmsType="1";
            } else if ("2".equals(getBankConfig().getValueAsString("signConfirm"))) {
                tmpReplySmsType="2";
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = "请检查节点配置：signConfirm";
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            xmlWriter.writeElementString("ReplySmsType",tmpReplySmsType);
            xmlWriter.writeElementString("CertCode", "");
            //扣款周期
            if("1".equals(p_req.contractDetail.periodLimit)){
                xmlWriter.writeElementString("Period", "D");
            }else if("2".equals(p_req.contractDetail.periodLimit)){
                xmlWriter.writeElementString("Period", "M");
            }else if("3".equals(p_req.contractDetail.periodLimit)){
                xmlWriter.writeElementString("Period", "Y");
            }else{
                xmlWriter.writeElementString("Period", "D");
            }
            if(StringHelper.hasAnyChar(p_req.contractDetail.insuPolicyNum)){
                xmlWriter.writeElementString("PolicyNumber", p_req.contractDetail.insuPolicyNum);
            }else{
                xmlWriter.writeElementString("PolicyNumber", p_req.contractDetail.sourceNoteCode);
            }
            xmlWriter.writeElementString("SignBusType","D30");
            xmlWriter.writeEndDocument();

            String[] tmpRetStr = sendToBank(xmlWriter.toXmlString());
            if (tmpRetStr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetStr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/Root/Head/RespCode");
                    String tmpRetMsg = tmpBkReader.getFirstText("/Root/Head/RespInfo");
                    tmpRetDetail.respCode = "0";
                    tmpRetDetail.respInfo = tmpBkReader.getFirstText("/Root/SignResp/ResultInfo");
                    String tmpState = tmpBkReader.getFirstText("/Root/SignResp/ResultState");
                    String tmpErrCode = "";
                    if ("2".equals(tmpState)) {
                        tmpRetDetail.deSignState = ContractState.SUCCESS;
                    }else if("3".equals(tmpState)){
                        tmpRetDetail.deSignState = ContractState.FAIL;
                    }else{
                        tmpRetDetail.respCode = "-1";
                        tmpRetDetail.deSignState = ContractState.SIGNING;
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpRetStr[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsDeContract qryDeContract(ReqDeContract p_reqQry) throws Exception {
        RetAtsDeContract retAts = new RetAtsDeContract(p_reqQry.reqHeader);
        RetAtsDeContractDetail tmpRetDetail = new RetAtsDeContractDetail();
        tmpRetDetail.reqSeqID = p_reqQry.contractDetail.askNumber;

        try {
            FnGrd01Header bankHeader = new FnGrd01Header();
            bankHeader.CorpBankCode = getBankConfig().getMapValueByKey("corBankCodeMapping", p_reqQry.contractDetail.recAct);
            if (StringHelper.isNullOrEmpty(bankHeader.CorpBankCode)) {
                WriteBankLogLn2("CorpBankCode为空，请配置corBankCodeMapping映射");
            }
            bankHeader.CommandCode="211A2";
            bankHeader.TransSeqID = getQryTransID();
            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("SignQueryReq");
            xmlWriter.writeElementString("Flag", "1");/* 0:签约 1:解约*/
            xmlWriter.writeElementString("CorpAct", p_reqQry.contractDetail.recAct);
            xmlWriter.writeElementString("ProtocolCode", p_reqQry.contractDetail.authCode);/* 协议号 	*/
            xmlWriter.writeElementString("CustAct", p_reqQry.contractDetail.payAct);
            xmlWriter.writeElementString("ForCommandCode", "111G1");
            xmlWriter.writeEndDocument();
            String[] tmpRetStr = sendToBank(xmlWriter.toXmlString());
            if (tmpRetStr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetStr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    tmpRetDetail.respCode = "0";
                    tmpRetDetail.respInfo = tmpBkReader.getFirstText("/Root/Head/RespInfo");

                    String tmpState = tmpBkReader.getFirstText("/Root/SignResp/ResultState");
                    if ("2".equals(tmpState)) {
                        // 解约约状态:2：解约成功，3：解约失败（具体错误原因）
                        tmpRetDetail.deSignState = ContractState.SUCCESS;
                    }else if("3".equals(tmpState)) {
                        tmpRetDetail.deSignState = ContractState.FAIL;
                        tmpRetDetail.respInfo=tmpBkReader.getFirstText("/Root/SignResp/RespInfo");
                    }else{
                        tmpRetDetail.respCode = "-1";
                        tmpRetDetail.respInfo=tmpBkReader.getFirstText("/Root/Head/RespInfo");
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpRetStr[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

}
